<script lang="ts" setup>
import type { Rule } from 'ant-design-vue/es/form';

import { onMounted, reactive, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { type FormInstance, message } from 'ant-design-vue';

import { Apis } from '#/api';
import { DICT_TYPE, dictUtils } from '#/utils/dict';

const props = defineProps<{
  module: 'comment' | 'post';
}>();

const emit = defineEmits(['success']);

export interface BanModalState {
  isUpdate: boolean;
  record: Record<string, any>;
}

type ModalState = BanModalState;

const data = ref<ModalState>();

const dictMap = reactive<any>({});

const form = reactive({});

const formRef = ref<FormInstance>();

const isLoading = ref(false);

const rules: Record<string, Rule[]> = {};

watch(
  () => form.unit,
  (newVal) => {
    if (newVal === 'forever') {
      form.second = null;
    }
  },
);

/** 时长单位 */
const timeUnitOptions = [
  { label: '分钟', value: 'minute' },
  { label: '小时', value: 'hour' },
  { label: '天', value: 'day' },
  { label: '永久', value: 'forever' },
];

const moduleMap = {
  post: '帖子',
  comment: '评论',
  reply: '回复',
};

function calculateSeconds() {
  const { unit, second } = form;

  if (unit === 'forever') {
    form.totalSeconds = 5 * 365 * 24 * 60 * 60; // 永久禁言
  } else if (unit && second > 0) {
    switch (unit) {
      case 'day': {
        form.totalSeconds = second * 86_400;
        break;
      }
      case 'hour': {
        form.totalSeconds = second * 3600;
        break;
      }
      case 'minute': {
        form.totalSeconds = second * 60;
        break;
      }
      default: {
        form.totalSeconds = 0;
      }
    }
  } else {
    form.totalSeconds = 0; // 如果时长未填写或无效，默认为 0
  }
}

const [BaseModal, baseModalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = baseModalApi.getData<Record<string, any>>();
    }
  },
  onConfirm: onSubmit,
});

async function onSubmit() {
  try {
    if (props.module === 'post') {
      await Apis.forum.post.delete({
        pathParams: {
          id: data.value.businessId,
        },
      });
      message.success({
        content: `帖子删除成功`,
      });
    }

    if (props.module === 'comment') {
      await Apis.forum.comment.delete({
        pathParams: {
          id: data.value.businessId,
        },
      });
      message.success({
        content: `评论删除成功`,
      });
    }

    if (props.module === 'reply') {
      await Apis.forum.reply.delete({
        pathParams: {
          id: data.value.businessId,
        },
      });
      message.success({
        content: `评论删除成功`,
      });
    }

    if (form.isMuted) {
      calculateSeconds();
      await Apis.system.user.setSilence({
        pathParams: {
          id: data.value.userId,
        },
        data: {
          userId: data.value.userId,
          second: form.totalSeconds,
        },
      });
      message.success({
        content: `用户禁言成功`,
      });
    }
    baseModalApi.close();
    emit('success');
  } catch (error) {
    console.error('表单验证失败:', error);
  }
}

function initForm() {}

onMounted(async () => {
  dictMap.value = await dictUtils.getDictDatasAsync([
    { type: DICT_TYPE.sysCommonStatus, valueType: 'number' },
    { type: DICT_TYPE.sysCommonWhether, valueType: 'number' },
    { type: DICT_TYPE.sysCommonColorType, valueType: 'string' },
  ]);
  initForm();
});
</script>
<template>
  <BaseModal :title="`${moduleMap[props.module]}封禁`" class="w-[600px]">
    <a-form
      ref="formRef"
      :label-col="{ style: 'width: 120px' }"
      :model="form"
      :rules="rules"
      class="grid-cols-1"
      label-class="w-full"
      layout="horizontal"
    >
      <!-- 用户昵称 -->
      <a-form-item
        :rules="[{ required: true, message: '用户昵称是必填项' }]"
        label="用户昵称"
        name="nickname"
      >
        <a-input
          v-model:value="data.nickname"
          class="w-full"
          placeholder=""
          readonly
        />
      </a-form-item>

      <!-- 封禁类型 -->
      <a-form-item
        :rules="[{ required: true, message: '请选择封禁类型' }]"
        label="封禁类型"
        name="banType"
      >
        <a-radio-group v-model:value="form.banType" class="w-full">
          <a-radio value="advertising">广告营销</a-radio>
          <a-radio value="violence">暴力低俗</a-radio>
          <a-radio value="abusive_language">言语辱骂</a-radio>
          <a-radio value="defamation">造谣诽谤</a-radio>
          <a-radio value="other">其它</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 封禁原因 -->
      <a-form-item label="封禁原因" name="banReason">
        <a-textarea
          v-model:value="form.banReason"
          :rows="4"
          placeholder="请填写封禁原因（如广告、违规内容等）"
        />
      </a-form-item>

      <!-- 是否禁言 -->
      <a-form-item label="是否禁言" name="isMuted">
        <a-switch
          v-model:checked="form.isMuted"
          checked-children="是"
          class="col-span-1"
          un-checked-children="否"
        />
      </a-form-item>

      <!-- 时长单位 -->
      <a-form-item label="时长单位" name="unit">
        <a-radio-group
          v-model:value="form.unit"
          :disabled="!form.isMuted"
          class="w-full"
        >
          <a-radio
            v-for="option in timeUnitOptions"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
          </a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 禁言时长 -->
      <a-form-item label="禁言时长" name="second">
        <a-input-number
          v-model:value="form.second"
          :addon-after="form.unit"
          :disabled="!form.isMuted || !form.unit || form.unit === 'forever'"
          :min="0"
          class="w-full"
          placeholder="请输入禁言时间"
        />
      </a-form-item>
    </a-form>
  </BaseModal>
</template>
